//
//  ContactTableViewController.m
//  WChat
//
//  Created by lw on 2018/7/28.
//  Copyright © 2018年 mjsfax. All rights reserved.
//

#import "ContactTableViewController.h"
#import "ChatViewController.h"
#import "ContactHeader.h"

@interface ContactTableViewController ()<IChatManagerDelegate>
@property (strong, nonatomic) NSMutableArray *friends;
@end

@implementation ContactTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    [self setup];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    [self queryFriends];
}

- (void)setup {
       self.title = @"通讯录";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStyleDone target:self action:@selector(addFriend)];
    ContactHeader *header = [ContactHeader instance];
    header.frame = CGRectMake(0, 0, SCREENWIDTH, 260);
    self.tableView.tableHeaderView = header;
}

- (void)addFriend {
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"好友申请" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"填写username";
    }];
    [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"填写理由";
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"发送" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //添加好友请求
        EMError *error = nil;
        BOOL isSuccess = [[EaseMob sharedInstance].chatManager addBuddy:alertVc.textFields.firstObject.text message:alertVc.textFields.lastObject.text error:&error];
        if (!error) {
            NSLog(@"发送好友请求成功 %d",isSuccess);
        }
    }];
    [alertVc addAction:action];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVc addAction:cancel];
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (void)queryFriends {
    [[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {
        if (error) {
            NSLog(@"%@",error);
            return;
        }
        self.friends = [NSMutableArray arrayWithArray:buddyList];
        [self.tableView reloadData];
    } onQueue:nil];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.friends.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"friends" forIndexPath:indexPath];
    EMBuddy *buddy = [self.friends objectAtIndex:indexPath.row];
    cell.textLabel.text = buddy.username;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ChatViewController *chat = [[ChatViewController alloc] init];
    EMBuddy *buddy = [self.friends objectAtIndex:indexPath.row];
    chat.username = buddy.username;
    [self.navigationController pushViewController:chat animated:YES];
}

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - easeMob delegate

- (void)didUpdateBuddyList:(NSArray *)buddyList changedBuddies:(NSArray *)changedBuddies isAdd:(BOOL)isAdd {
    NSLog(@"%@==%@",buddyList, changedBuddies);
    [self.friends removeAllObjects];
    [self.friends addObjectsFromArray:buddyList];
    [self.tableView reloadData];
}

- (NSMutableArray *)friends {
    if (!_friends) {
        _friends = [NSMutableArray array];
    }
    return _friends;
}

@end
